package usersDao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {
	private DBUtils() {

	}

	private static final String URl = "jdbc:mysql://localhost:3306/sql?useSSL=false";

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		try {
			Connection conn = DriverManager.getConnection(URl, "root", "1234");
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void close(ResultSet rs, PreparedStatement pst, Connection conn) {
		close(rs);
		close(pst);
		close(conn);
	}

	public static void close(ResultSet rs) {
		try {
			if (null != rs) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void close(PreparedStatement pst) {
		try {
			if (null != pst) {
				pst.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void close(Connection conn) {
		try {
			if (null != conn) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static int executeUpdate(String sql, Object... o) {
		Connection conn = getConnection();
		PreparedStatement st = null;
		int r = 0;
		try {
			st = conn.prepareStatement(sql);
			for (int i = 0; i < o.length; i++) {
				st.setObject(i + 1, o[i]);
			}
			r = st.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(st);
			close(conn);
		}
		return r;
	}
}